package com.yjd.comm.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.yjd.comm.fs.model.FileUploadedModel;
import com.yjd.comm.fs.model.FsFileModel;
import org.apache.log4j.Logger;

import javax.activation.MimetypesFileTypeMap;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 阿里OSS工具类
 * Created by zhoujin on 2016/11/16.
 */
public class OSSClientUtil {
    protected static Logger logger = Logger.getLogger(OSSClientUtil.class.getName());

    private static OSSClient ossClient = null;

    private OSSClientUtil() {

    }

    /**
     * 初始化
     */
    public static synchronized void init() {
        String endpoint = FrameUtil.getConstResource("EndPoint");
        String accessKeyId = FrameUtil.getConstResource("AccessKeyID");
        String accessKeySecret = FrameUtil.getConstResource("AccessKeySecret");
        if(ossClient == null){
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        }
    }

    /**
     * 查询文件列表
     */
    public static List<FsFileModel> listBucketObject(String prefix) {
        String bucket = FrameUtil.getConstResource("Bucket");
        init();
        ObjectListing bucketContent = null;
        if(StringUtil.isEmpty(prefix)){
            bucketContent = ossClient.listObjects(bucket);
        } else {
            bucketContent = ossClient.listObjects(bucket, prefix);
        }

        List<FsFileModel> files = new ArrayList<FsFileModel>();
        FsFileModel f = null;
        for(OSSObjectSummary osy : bucketContent.getObjectSummaries()){
            f = new FsFileModel();
            f.setOriginalFileName(osy.getKey());
            f.setFileSize(osy.getSize());
            f.setCreateTime(osy.getLastModified().getTime());
            f.setFilePath(osy.getBucketName());
            files.add(f);
        }

        return files;
    }

    /**
     * 销毁
     */
    public static void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param temp 文件
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public static FileUploadedModel uploadFile2OSS(File temp, String fileName) {
        init();
        FileInputStream fls = null;
        FileUploadedModel fum = null;
        try {
            fileName = FrameUtil.getConstResource("FileDir") + fileName;
            fls = new FileInputStream(temp);
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(fls.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".") + 1)));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            String bucketName =  FrameUtil.getConstResource("Bucket");
            PutObjectResult putResult = ossClient.putObject(bucketName, fileName, fls, objectMetadata);

            fum = new FileUploadedModel();
            fum.setAttachment(fileName);
            fum.setAttachurl(getUrl(fileName));
            fum.setId(fileName.substring(0, fileName.lastIndexOf(".")));
            fum.setSize(temp.length());
            fum.setExt(fileName.substring(fileName.lastIndexOf(".")+1));
            fum.setTemp_name(temp.getName());
            fum.setType(new MimetypesFileTypeMap().getContentType(temp));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (fls != null) {
                    fls.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return fum;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase("apk")) {
            return "application/vnd.android.package-archive";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        String bucketName =  FrameUtil.getConstResource("Bucket");
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
}